package com.example.highway.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.highway.config.MyJson;
import com.example.highway.dao.OwnerDao;
import com.example.highway.dao.TaskAssignDao;
import com.example.highway.entity.Owner;
import com.example.highway.entity.OwnerCar;
import com.example.highway.entity.TaskAssign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Optional;

@RestController
@CrossOrigin
@RequestMapping("task-assign")
public class TaskAssignController {
    @Autowired
    TaskAssignDao taskAssignDao;

    @RequestMapping("add")
    public MyJson add(@RequestBody() String msg){
        JSONObject jsonObject = JSON.parseObject(msg);

        TaskAssign taskAssign = taskAssignDao.save(jsonObject.toJavaObject(TaskAssign.class));
        JSONObject rtn = new JSONObject();
        rtn.put("id", taskAssign.getId());

        return new MyJson("0", rtn);
    }

    @RequestMapping("get")
    public MyJson one(@RequestBody() String msg){
        JSONObject jsonObject = JSON.parseObject(msg);

//        if(jsonObject.containsKey("id")){
//            Optional<TaskAssign> o = taskAssignDao.findById((String)jsonObject.get("id"));
//            if(!o.isPresent()){
//                return new MyJson("0", null);
//            }else {
//                TaskAssign taskAssign = o.get();
//                return new MyJson("0", taskAssign);
//            }
//        }
//        TaskAssign taskAssign = jsonObject.toJavaObject(TaskAssign.class);
//
//        List<TaskAssign> ownerCarList = taskAssignDao.findAll(Example.of(taskAssign));

        TaskAssign taskAssign = jsonObject.toJavaObject(TaskAssign.class);
        List<TaskAssign> taskAssigns = taskAssignDao.findAll(Example.of(taskAssign));
        return new MyJson("0", JSONArray.toJSON(taskAssigns));

    }

//    @RequestMapping("get-all")
//    public MyJson all(){
//        List<TaskAssign> o = taskAssignDao.findAll();
//        if(o.isEmpty()){
//            return new MyJson("0", null);
//        }
//
//        return new MyJson("0", o);
//
//    }
}
